// dashboard.js
// 领导驾驶舱核心交互与图表渲染脚本
// 主要功能：模态框穿透、图表渲染入口、静态数据结构示例
// 所有内容均有中文注释，便于理解和维护

// =====================
// 1. 模态框穿透查询逻辑
// =====================
const modal = document.getElementById('detailModal');
const modalTitle = document.getElementById('modalTitle');
const modalContent = document.getElementById('modalContent');
const closeModal = document.getElementById('closeModal');
const closeModalBtn = document.getElementById('closeModalBtn');

// 打开模态框，type为指标标识
window.showDetail = function (type) {
    modal.classList.remove('hidden');
    // 根据type填充不同内容
    renderModalContent(type);
};

closeModal.onclick = closeModalBtn.onclick = function () {
    modal.classList.add('hidden');
};

// =====================
// 2. 模态内容渲染（全覆盖）
// =====================
function renderModalContent(type) {
    // 这里只做结构演示，实际可根据type加载不同图表/表格
    let title = '';
    let html = '';
    switch (type) {
        // 客户消费分析
        case 'recency':
            title = '平均消费天数 - 年度趋势与TOP5分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>指标解读</b><br>
                    最近消费天数 (Recency) 反映了客户的活跃状态。该值越小，表示客户最近一次购买行为距离现在越近，活跃度越高，对品牌的记忆和粘性也越强。<br><br>
                    通过分析Recency的分布，我们可以识别出近期活跃的核心客户群体，以及长时间未消费、可能面临流失风险的客户。这为我们制定差异化的营销和关怀策略提供了数据支持。
                </div>
                <div class="flex flex-col md:flex-row gap-4 items-stretch">
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">年度趋势</h4>
                        <canvas id="modalRecencyChart" height="120"></canvas>
                    </div>
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">最近消费客户TOP5</h4>
                        <canvas id="modalRecentTop5Chart" height="120"></canvas>
                    </div>
                </div>
            `;
            setTimeout(() => {
                // 年度趋势曲线图（平滑）
                new Chart(document.getElementById('modalRecencyChart'), {
                    type: 'line',
                    data: {
                        labels: ['2019', '2020', '2021', '2022', '2023'],
                        datasets: [{
                            label: '平均消费天数',
                            data: [22, 25, 14, 18, 16],
                            borderColor: '#165DFF',
                            backgroundColor: 'rgba(22,93,255,0.1)',
                            fill: true,
                            tension: 0.4 // 平滑曲线
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { display: true } },
                        scales: {
                            x: { grid: { display: false }, ticks: { color: '#86909C' }, title: { display: true, text: '年份' } },
                            y: { grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { color: '#86909C' }, title: { display: true, text: '消费间隔（天）' }  }
                        }
                    }
                });
                // 水平条形图，按数值从大到小排列
                const top5Labels = ['客户E', '客户A', '客户B', '客户D', '客户C'];
                const top5Data = [5, 7, 9, 12, 15];
                new Chart(document.getElementById('modalRecentTop5Chart'), {
                    type: 'bar',
                    data: {
                        labels: top5Labels,
                        datasets: [{
                            label: '消费间隔（天）',
                            data: top5Data,
                            backgroundColor: '#0FC6C2'
                        }]
                    },
                    options: {
                        indexAxis: 'y', // 水平
                        responsive: true,
                        plugins: { legend: { display: false } },
                        scales: {
                            x: { grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { color: '#86909C' }, title: { display: true, text: '消费间隔（天）' } },
                            y: { grid: { display: false }, ticks: { color: '#86909C' }, title: { display: true, text: '客户' } }
                        }
                    }
                });
            }, 100);
            break;
        case 'frequency':
            title = '平均消费频率 - 趋势分析';
            html = `<canvas id="modalFrequencyChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalFrequencyChart', '平均消费频率', [3.8, 4.0, 4.1, 4.2, 4.2]), 100);
            break;
        case 'monetary':
            title = '客均消费金额 - 趋势分析';
            html = `<canvas id="modalMonetaryChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalMonetaryChart', '客均消费金额', [3500, 3700, 3800, 3850, 3900]), 100);
            break;
        case 'avgOrder':
            title = '单均消费金额 - 趋势分析';
            html = `<canvas id="modalAvgOrderChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalAvgOrderChart', '单均消费金额', [800, 850, 900, 916, 950]), 100);
            break;
        case 'rfmScore':
            title = 'RFM总分平均值 - 趋势分析';
            html = `<canvas id="modalRfmScoreChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalRfmScoreChart', 'RFM总分平均值', [3.5, 3.6, 3.7, 3.8, 3.9]), 100);
            break;
        case 'highValueRatio':
            title = '高价值客户占比 - 趋势分析';
            html = `<canvas id="modalHighValueRatioChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalHighValueRatioChart', '高价值客户占比', [20, 22, 23, 25, 25.3]), 100);
            break;
        case 'importantMaintain':
            title = '重要保持客户数量 - 趋势分析';
            html = `<canvas id="modalImportantMaintainChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalImportantMaintainChart', '重要保持客户数量', [800, 850, 900, 920, 935]), 100);
            break;
        case 'consumptionTrend':
            title = '客均/单均消费金额与变化率趋势图';
            html = `<canvas id="modalConsumptionTrendChart" height="300"></canvas>`;
            setTimeout(() => renderMultiLineChart('modalConsumptionTrendChart', ['客均消费金额', '单均消费金额'], [[3500, 3700, 3800, 3850, 3900], [800, 850, 900, 916, 950]]), 100);
            break;
        // 客户结构分析
        case 'customerCategory':
            title = '客户类型统计分析';
            html = `
                <div class="flex flex-col md:flex-row gap-4 items-stretch">
                    <!-- 左侧文字描述 -->
                    <div class="flex-1 bg-light rounded-lg p-4 flex flex-col justify-center">
                        <h4 class="text-md font-medium mb-2">指标解读</h4>
                        <p class="text-sm text-gray-700 leading-relaxed">
                            客户类型统计表格综合展示了不同客户类型的数量、消费能力、活跃度等核心特征。通过对比各类型客户的人均消费金额、消费频率和最近消费天数，可以精准识别高价值客户群体和潜力客户，为差异化营销和资源分配提供数据支撑。<br><br>
                            行动优先级建议：优先维护重要价值客户和重要保持客户，重点挖掘重要发展客户，及时挽留重要挽留客户，适度关注一般和低价值客户。
                        </p>
                    </div>
                    <!-- 右侧统计表格 -->
                    <div class="flex-1 bg-white rounded-lg p-4 overflow-x-auto">
                        <table class="w-full text-sm">
                            <thead>
                                <tr class="border-b border-gray-200">
                                    <th class="py-2 text-left">客户类型</th>
                                    <th class="py-2 text-right">客户数量</th>
                                    <th class="py-2 text-right">人均消费金额</th>
                                    <th class="py-2 text-right">消费频率</th>
                                    <th class="py-2 text-right">最近消费天数</th>
                                    <th class="py-2 text-right">占比</th>
                                    <th class="py-2 text-center">行动优先级</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="border-b border-gray-100">
                                    <td class="py-2">重要价值客户</td>
                                    <td class="py-2 text-right">1,265</td>
                                    <td class="py-2 text-right">¥8,650</td>
                                    <td class="py-2 text-right">12次/月</td>
                                    <td class="py-2 text-right">5天</td>
                                    <td class="py-2 text-right">25.3%</td>
                                    <td class="py-2 text-center"><span class="px-2 py-1 bg-primary/10 text-primary text-xs rounded-full">最高</span></td>
                                </tr>
                                <tr class="border-b border-gray-100">
                                    <td class="py-2">重要保持客户</td>
                                    <td class="py-2 text-right">935</td>
                                    <td class="py-2 text-right">¥7,240</td>
                                    <td class="py-2 text-right">10次/月</td>
                                    <td class="py-2 text-right">8天</td>
                                    <td class="py-2 text-right">18.7%</td>
                                    <td class="py-2 text-center"><span class="px-2 py-1 bg-secondary/10 text-secondary text-xs rounded-full">高</span></td>
                                </tr>
                                <tr class="border-b border-gray-100">
                                    <td class="py-2">重要发展客户</td>
                                    <td class="py-2 text-right">760</td>
                                    <td class="py-2 text-right">¥5,980</td>
                                    <td class="py-2 text-right">7次/月</td>
                                    <td class="py-2 text-right">12天</td>
                                    <td class="py-2 text-right">15.2%</td>
                                    <td class="py-2 text-center"><span class="px-2 py-1 bg-warning/10 text-warning text-xs rounded-full">中</span></td>
                                </tr>
                                <tr class="border-b border-gray-100">
                                    <td class="py-2">重要挽留客户</td>
                                    <td class="py-2 text-right">640</td>
                                    <td class="py-2 text-right">¥4,120</td>
                                    <td class="py-2 text-right">5次/月</td>
                                    <td class="py-2 text-right">25天</td>
                                    <td class="py-2 text-right">12.8%</td>
                                    <td class="py-2 text-center"><span class="px-2 py-1 bg-danger/10 text-danger text-xs rounded-full">高</span></td>
                                </tr>
                                <tr class="border-b border-gray-100">
                                    <td class="py-2">一般价值客户</td>
                                    <td class="py-2 text-right">525</td>
                                    <td class="py-2 text-right">¥2,850</td>
                                    <td class="py-2 text-right">3次/月</td>
                                    <td class="py-2 text-right">35天</td>
                                    <td class="py-2 text-right">10.5%</td>
                                    <td class="py-2 text-center"><span class="px-2 py-1 bg-info/10 text-info text-xs rounded-full">低</span></td>
                                </tr>
                                <tr>
                                    <td class="py-2">低价值客户</td>
                                    <td class="py-2 text-right">875</td>
                                    <td class="py-2 text-right">¥1,200</td>
                                    <td class="py-2 text-right">1次/月</td>
                                    <td class="py-2 text-right">60天</td>
                                    <td class="py-2 text-right">17.5%</td>
                                    <td class="py-2 text-center"><span class="px-2 py-1 bg-gray-200 text-gray-600 text-xs rounded-full">最低</span></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
            break;
        case 'topCustomers':
            title = '高价值客户TOP10 - 柱状图';
            html = `<canvas id="modalTopCustomersChart" height="300"></canvas>`;
            setTimeout(() => renderBarChart('modalTopCustomersChart', ['客户1', '客户2', '客户3', '客户4', '客户5', '客户6', '客户7', '客户8', '客户9', '客户10'], [286500, 254300, 218700, 195200, 182400, 156800, 145300, 132700, 125600, 118900]), 100);
            break;
        // 财务相关
        case 'paymentRate':
            title = '回款及时率 - 趋势分析';
            html = `<canvas id="modalPaymentRateChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPaymentRateChart', '回款及时率', [90, 91, 92, 92.5, 93]), 100);
            break;
        case 'priceChange':
            title = '单价变动率 - 趋势分析';
            html = `<canvas id="modalPriceChangeChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPriceChangeChart', '单价变动率', [2.5, 2.8, 3.0, 3.2, 3.5]), 100);
            break;
        case 'quantityChange':
            title = '数量变动率 - 趋势分析';
            html = `<canvas id="modalQuantityChangeChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalQuantityChangeChart', '数量变动率', [5, 6, 7, 8.7, 9]), 100);
            break;
        case 'totalAmount':
            title = '合作总金额 - 趋势分析';
            html = `<canvas id="modalTotalAmountChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalTotalAmountChart', '合作总金额', [2.1, 2.3, 2.5, 2.8, 3.0]), 100);
            break;
        case 'receivables':
            title = '应收款金额 - 趋势分析';
            html = `<canvas id="modalReceivablesChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalReceivablesChart', '应收款金额', [400, 420, 430, 456, 470]), 100);
            break;
        case 'billRatio':
            title = '票据占比 - 趋势分析';
            html = `<canvas id="modalBillRatioChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalBillRatioChart', '票据占比', [15, 16, 17, 18.5, 19]), 100);
            break;
        case 'inventory':
            title = '库存金额 - 趋势分析';
            html = `<canvas id="modalInventoryChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalInventoryChart', '库存金额', [200, 210, 220, 234, 240]), 100);
            break;
        case 'financialTrend':
            title = '财务趋势 - 多指标对比';
            html = `<canvas id="modalFinancialTrendChart" height="300"></canvas>`;
            setTimeout(() => renderMultiLineChart('modalFinancialTrendChart', ['回款率', '应收款'], [[90, 91, 92, 92.5, 93], [400, 420, 430, 456, 470]]), 100);
            break;
        // 质量与交付
        case 'qualityRate':
            title = '质量合格率 - 趋势分析';
            html = `<canvas id="modalQualityRateChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalQualityRateChart', '质量合格率', [97, 97.5, 98, 98.7, 99]), 100);
            break;
        case 'deliveryCycle':
            title = '平均交付周期 - 趋势分析';
            html = `<canvas id="modalDeliveryCycleChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalDeliveryCycleChart', '平均交付周期', [15, 14, 13, 12.5, 12]), 100);
            break;
        case 'deliveryModel':
            title = '交付型号数量 - 趋势分析';
            html = `<canvas id="modalDeliveryModelChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalDeliveryModelChart', '交付型号数量', [120, 130, 140, 156, 160]), 100);
            break;
        case 'deliveryResearch':
            title = '交付预研数量 - 趋势分析';
            html = `<canvas id="modalDeliveryResearchChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalDeliveryResearchChart', '交付预研数量', [60, 70, 80, 89, 95]), 100);
            break;
        case 'deliveryHorizontal':
            title = '交付横向数量 - 趋势分析';
            html = `<canvas id="modalDeliveryHorizontalChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalDeliveryHorizontalChart', '交付横向数量', [50, 55, 60, 67, 70]), 100);
            break;
        case 'deliveryCivil':
            title = '交付民品数量 - 趋势分析';
            html = `<canvas id="modalDeliveryCivilChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalDeliveryCivilChart', '交付民品数量', [180, 200, 210, 234, 240]), 100);
            break;
        // 客户动态
        case 'newCustomers':
            title = '新增客户数量 - 趋势分析';
            html = `<canvas id="modalNewCustomersChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalNewCustomersChart', '新增客户数量', [100, 120, 130, 156, 160]), 100);
            break;
        case 'lostCustomers':
            title = '退出客户数量 - 趋势分析';
            html = `<canvas id="modalLostCustomersChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalLostCustomersChart', '退出客户数量', [30, 28, 25, 23, 20]), 100);
            break;
        // 二级穿透查询区块
        case 'rfmTrend':
            title = 'RFM总分平均值趋势 - 折线图';
            html = `<canvas id="modalRfmTrendChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalRfmTrendChart', 'RFM总分平均值', [3.5, 3.6, 3.7, 3.8, 3.9]), 100);
            break;
        case 'consumptionTrend':
            title = '客均/单均消费金额趋势 - 折线图';
            html = `<canvas id="modalConsumptionTrend2Chart" height="300"></canvas>`;
            setTimeout(() => renderMultiLineChart('modalConsumptionTrend2Chart', ['客均消费金额', '单均消费金额'], [[3500, 3700, 3800, 3850, 3900], [800, 850, 900, 916, 950]]), 100);
            break;
        case 'rfmDistribution':
            title = '客户RFM分布 - 散点图';
            html = `<canvas id="modalRfmScatter" height="300"></canvas>`;
            setTimeout(() => renderScatterChart('modalRfmScatter'), 100);
            break;
        case 'rfmComparison':
            title = '客户RFM对比 - 雷达图';
            html = `<canvas id="modalRfmRadar" height="300"></canvas>`;
            setTimeout(() => renderRadarChart('modalRfmRadar'), 100);
            break;
        case 'rfmHeatmap':
            title = '客户RFM热力图';
            html = `<canvas id="modalRfmHeatmap" height="300"></canvas>`;
            setTimeout(() => renderHeatmap('modalRfmHeatmap'), 100);
            break;
        case 'paretoAnalysis':
            title = '客户类型帕累托分析 - 组合图';
            html = `<canvas id="modalParetoChart" height="300"></canvas>`;
            setTimeout(() => renderParetoChart('modalParetoChart'), 100);
            break;
        case 'frequencyTop5':
            title = '消费频率客户TOP5 - 柱状图';
            html = `<canvas id="modalFrequencyTop5Chart" height="300"></canvas>`;
            setTimeout(() => renderBarChart('modalFrequencyTop5Chart', ['客户A', '客户B', '客户C', '客户D', '客户E'], [12, 10, 9, 8, 7]), 100);
            break;
        case 'paymentTrend':
            title = '回款及时率趋势 - 折线图';
            html = `<canvas id="modalPaymentTrendChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPaymentTrendChart', '回款及时率', [90, 91, 92, 92.5, 93]), 100);
            break;
        case 'receivablesTrend':
            title = '应收款金额趋势 - 折线图';
            html = `<canvas id="modalReceivablesTrendChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalReceivablesTrendChart', '应收款金额', [400, 420, 430, 456, 470]), 100);
            break;
        default:
            title = '详细分析';
            html = '<div>暂无详细内容</div>';
    }
    modalTitle.innerText = title;
    modalContent.innerHTML = html;
}

// =====================
// 3. 图表渲染入口（Chart.js）
// =====================
// 折线图示例
function renderLineChart(canvasId, label, data, labels) {
    new Chart(document.getElementById(canvasId), {
        type: 'line',
        data: {
            labels: labels || ['一月', '二月', '三月', '四月', '五月'],
            datasets: [{
                label: label,
                data: data,
                borderColor: '#165DFF',
                backgroundColor: 'rgba(22,93,255,0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: true } }
        }
    });
}
// 多折线图
function renderMultiLineChart(canvasId, labelsArr, dataArr, xLabels) {
    const colors = ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F'];
    new Chart(document.getElementById(canvasId), {
        type: 'line',
        data: {
            labels: xLabels || ['一月', '二月', '三月', '四月', '五月'],
            datasets: labelsArr.map((label, i) => ({
                label: label,
                data: dataArr[i],
                borderColor: colors[i % colors.length],
                backgroundColor: colors[i % colors.length] + '22',
                fill: false,
                tension: 0.4
            }))
        },
        options: {
            responsive: true,
            plugins: { legend: { display: true } }
        }
    });
}
// 柱状图
function renderBarChart(canvasId, labels, data) {
    new Chart(document.getElementById(canvasId), {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: '数值',
                data: data,
                backgroundColor: '#165DFF',
            }]
        },
        options: { responsive: true }
    });
}
// 饼图
function renderPieChart(canvasId, labels, data) {
    new Chart(document.getElementById(canvasId), {
        type: 'pie',
        data: {
            labels: labels,
            datasets: [{
                data: data,
                backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#00B42A'],
            }]
        },
        options: { responsive: true }
    });
}
// 散点图
function renderScatterChart(canvasId) {
    new Chart(document.getElementById(canvasId), {
        type: 'scatter',
        data: {
            datasets: [{
                label: '客户分布',
                data: [{ x: 10, y: 200 }, { x: 20, y: 400 }, { x: 30, y: 300 }, { x: 40, y: 500 }],
                backgroundColor: '#0FC6C2'
            }]
        },
        options: { responsive: true }
    });
}
// 雷达图
function renderRadarChart(canvasId) {
    new Chart(document.getElementById(canvasId), {
        type: 'radar',
        data: {
            labels: ['R', 'F', 'M'],
            datasets: [
                { label: '高价值客户', data: [5, 5, 5], backgroundColor: 'rgba(22,93,255,0.2)', borderColor: '#165DFF' },
                { label: '普通客户', data: [3, 2, 2], backgroundColor: 'rgba(15,198,194,0.2)', borderColor: '#0FC6C2' }
            ]
        },
        options: { responsive: true }
    });
}
// 热力图（用色块模拟）
function renderHeatmap(canvasId) {
    // 这里只做简单色块模拟，实际可用插件或自定义实现
    const ctx = document.getElementById(canvasId).getContext('2d');
    for (let i = 0; i < 5; i++) {
        for (let j = 0; j < 5; j++) {
            ctx.fillStyle = `rgba(22,93,255,${0.2 + 0.15 * i + 0.1 * j})`;
            ctx.fillRect(40 * i, 40 * j, 38, 38);
        }
    }
}
// 帕累托组合图
function renderParetoChart(canvasId) {
    new Chart(document.getElementById(canvasId), {
        type: 'bar',
        data: {
            labels: ['类型A', '类型B', '类型C', '类型D', '类型E'],
            datasets: [
                {
                    label: '消费金额',
                    data: [100, 80, 60, 40, 20],
                    backgroundColor: '#165DFF',
                    yAxisID: 'y',
                },
                {
                    label: '累计占比',
                    data: [20, 40, 65, 85, 100],
                    type: 'line',
                    borderColor: '#FF7D00',
                    backgroundColor: 'rgba(255,125,0,0.1)',
                    yAxisID: 'y1',
                }
            ]
        },
        options: {
            responsive: true,
            scales: {
                y: { beginAtZero: true, position: 'left', title: { display: true, text: '金额' } },
                y1: { beginAtZero: true, position: 'right', title: { display: true, text: '累计占比(%)' }, grid: { drawOnChartArea: false } }
            }
        }
    });
}

// =====================
// 4. 静态数据结构示例
// =====================
// 如需对接真实数据，可在此定义数据结构
// const kpiData = { ... };
// 当前未直接使用，已注释避免linter报错

// =====================
// 5. 页面加载后可自动渲染首页主要图表
// =====================
window.onload = function () {
    // 首页主要图表渲染
    if (document.getElementById('rfmTrendChart')) {
        // RFM总分平均值趋势，x轴为年份，y轴为固定有起伏的示例值
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const rfmData = [3.5, 3.8, 3.6, 3.9, 3.7];
        renderLineChart('rfmTrendChart', 'RFM总分平均值', rfmData, years);
    }
    if (document.getElementById('consumptionTrendChart')) {
        // 客均/单均消费金额趋势，x轴为年份，y轴为固定有起伏的示例值
        const years = ['2019', '2020', '2021', '2022', '2023'];
        const data1 = [3500, 3700, 3600, 3850, 3750]; // 客均消费金额
        const data2 = [800, 900, 850, 950, 900];      // 单均消费金额
        renderMultiLineChart('consumptionTrendChart', ['客均消费金额', '单均消费金额'], [data1, data2], years);
    }
    if (document.getElementById('customerCategoryChart')) {
        renderPieChart('customerCategoryChart', ['VIP', '重要保持', '重要发展', '一般', '低价值'], [25, 18, 15, 10, 32]);
    }
    if (document.getElementById('rfmScatterChart')) {
        renderScatterChart('rfmScatterChart');
    }
    if (document.getElementById('rfmRadarChart')) {
        renderRadarChart('rfmRadarChart');
    }
    if (document.getElementById('paretoChart')) {
        renderParetoChart('paretoChart');
    }
    if (document.getElementById('recentTop5Chart')) {
        renderBarChart('recentTop5Chart', ['客户A', '客户B', '客户C', '客户D', '客户E'], [5, 4, 3, 2, 1]);
    }
    if (document.getElementById('frequencyTop5Chart')) {
        renderBarChart('frequencyTop5Chart', ['客户A', '客户B', '客户C', '客户D', '客户E'], [12, 10, 9, 8, 7]);
    }
    if (document.getElementById('paymentTrendChart')) {
        renderLineChart('paymentTrendChart', '回款及时率', [90, 91, 92, 92.5, 93]);
    }
    if (document.getElementById('receivablesTrendChart')) {
        renderLineChart('receivablesTrendChart', '应收款金额', [400, 420, 430, 456, 470]);
    }
    // 其余首页图表可依次补全

    // 侧边栏折叠/展开功能
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainContent');
    const toggleSidebar = document.getElementById('toggleSidebar');
    if (sidebar && mainContent && toggleSidebar) {
        toggleSidebar.onclick = function () {
            // 切换侧边栏宽度
            sidebar.classList.toggle('w-64');
            sidebar.classList.toggle('w-16');
            // 切换主内容区左边距
            mainContent.classList.toggle('pl-64');
            mainContent.classList.toggle('pl-16');
            // 切换侧边栏内文字显示
            sidebar.classList.toggle('sidebar-collapsed');
        };
    }

    // 渲染客户类型占比环形图
    const customerTypeChartDom = document.getElementById('customerTypeChart');
    if (customerTypeChartDom) {
        const customerTypeCtx = customerTypeChartDom.getContext('2d');
        new Chart(customerTypeCtx, {
            type: 'doughnut',
            data: {
                labels: ['重要价值客户', '重要保持客户', '重要发展客户', '重要挽留客户', '一般价值客户', '低价值客户'],
                datasets: [{
                    data: [25.3, 18.7, 15.2, 12.8, 10.5, 17.5],
                    backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C', '#C9CDD4'],
                    borderWidth: 0,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                const label = context.label || '';
                                const value = context.parsed || 0;
                                return `${label}: ${value}%`;
                            }
                        }
                    }
                },
                animation: {
                    animateRotate: true,
                    animateScale: true
                },
                onHover: (event, chartElement) => {
                    event.native.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
                }
            }
        });
        // 点击环形图弹出二级穿透查询弹窗
        customerTypeChartDom.onclick = function () {
            showDetail('customerCategory');
        };
    }

    // 客户类型帕累托分析
    const customerTypeParetoDom = document.getElementById('customerTypeParetoChart');
    if (customerTypeParetoDom) {
        const ctx = customerTypeParetoDom.getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['重要价值客户', '重要保持客户', '重要发展客户', '重要挽留客户', '一般价值客户', '低价值客户'],
                datasets: [
                    {
                        label: '消费金额(万元)',
                        data: [320, 240, 180, 140, 100, 80],
                        backgroundColor: '#165DFF',
                        borderWidth: 0,
                        yAxisID: 'y'
                    },
                    {
                        label: '累计消费占比',
                        data: [32, 56, 74, 88, 98, 100],
                        borderColor: '#FF7D00',
                        backgroundColor: 'rgba(255, 125, 0, 0.2)',
                        borderWidth: 2,
                        pointBackgroundColor: '#FF7D00',
                        pointRadius: 4,
                        type: 'line',
                        tension: 0.4,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { boxWidth: 12, padding: 15, color: '#4E5969', font: { size: 12 } }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                if (context.dataset.label === '消费金额(万元)') {
                                    return `${context.dataset.label}: ${context.raw}万元`;
                                } else {
                                    return `${context.dataset.label}: ${context.raw}%`;
                                }
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: '#86909C', font: { size: 10 }, autoSkip: false, maxRotation: 45, minRotation: 45 }
                    },
                    y: {
                        type: 'linear', display: true, position: 'left',
                        title: { display: true, text: '消费金额(万元)', color: '#86909C', font: { size: 12 } },
                        grid: { color: 'rgba(0, 0, 0, 0.05)' },
                        ticks: { color: '#86909C' }
                    },
                    y1: {
                        type: 'linear', display: true, position: 'right',
                        title: { display: true, text: '累计消费占比(%)', color: '#86909C', font: { size: 12 } },
                        grid: { drawOnChartArea: false },
                        ticks: { color: '#86909C', callback: function (value) { return value + '%'; } },
                        min: 0,
                        max: 100
                    }
                }
            }
        });
    }

    // 客户帕累托分析
    const customerParetoDom = document.getElementById('customerParetoChart');
    if (customerParetoDom) {
        const ctx = customerParetoDom.getContext('2d');
        // 示例数据：客户名称、金额、累计占比
        const labels = ['客户A', '客户B', '客户C', '客户D', '客户E', '客户F', '客户G', '客户H', '客户I', '客户J'];
        const amounts = [120, 110, 90, 80, 70, 60, 50, 40, 30, 20];
        const cumPercents = [12, 23, 32, 40, 47, 53, 58, 62, 65, 67];
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: '消费金额(万元)',
                        data: amounts,
                        backgroundColor: '#0FC6C2',
                        borderWidth: 0,
                        yAxisID: 'y'
                    },
                    {
                        label: '累计消费占比',
                        data: cumPercents,
                        borderColor: '#FF7D00',
                        backgroundColor: 'rgba(255, 125, 0, 0.2)',
                        borderWidth: 2,
                        pointBackgroundColor: '#FF7D00',
                        pointRadius: 4,
                        type: 'line',
                        tension: 0.4,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { boxWidth: 12, padding: 15, color: '#4E5969', font: { size: 12 } }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                if (context.dataset.label === '消费金额(万元)') {
                                    return `${context.dataset.label}: ${context.raw}万元`;
                                } else {
                                    return `${context.dataset.label}: ${context.raw}%`;
                                }
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: '#86909C', font: { size: 10 }, autoSkip: false, maxRotation: 45, minRotation: 45 }
                    },
                    y: {
                        type: 'linear', display: true, position: 'left',
                        title: { display: true, text: '消费金额(万元)', color: '#86909C', font: { size: 12 } },
                        grid: { color: 'rgba(0, 0, 0, 0.05)' },
                        ticks: { color: '#86909C' }
                    },
                    y1: {
                        type: 'linear', display: true, position: 'right',
                        title: { display: true, text: '累计消费占比(%)', color: '#86909C', font: { size: 12 } },
                        grid: { drawOnChartArea: false },
                        ticks: { color: '#86909C', callback: function (value) { return value + '%'; } },
                        min: 0,
                        max: 100
                    }
                }
            }
        });
    }
}; 